<?php

namespace app\api\controller;

use app\common\model\AccountRecordModel;
use app\common\model\CompanyConfigModel;
use think\App;
use app\common\model\CompanyModel;
use app\common\model\AccountModel;
use think\facade\Request;
use think\Db;
use app\common\model\ApplicationsModel;

/**  YSF
 *   企业API
 *   Date: 2019/1/4
 * Class Company
 * @package app\api\controller
 */
class Company extends Base
{
    protected $companyModel;
    protected $companyConfigModel;
    protected $accountRecordModel;
    protected $accountModel;
    protected $applicationsModel;

    // 初始化构造方法
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->companyModel = new CompanyModel();  // 企业模型
        $this->companyConfigModel = new CompanyConfigModel();  // 企业配置模型
        $this->accountRecordModel = new AccountRecordModel(); // 账户记录表模型
        $this->accountModel = new AccountModel(); // 账户表模型
        $this->applicationsModel = new ApplicationsModel(); // 账户表模型
    }

    // 企业列表
    public function getLists()
    {
        // 接收参数
        $page = $this->parm['page'] ?? 1;
        $pageSize = $this->parm['pageSize'] ?? 10;

        $where = [];
        if (!empty($this->parm['company_name'] ?? '')) {
            $where[] = ['company_name', 'LIKE', '%' . $this->parm['company_name'] . '%'];
        }
        if (!empty($this->parm['contacts'] ?? '')) {
            $where[] = ['contacts', 'LIKE', '%' . $this->parm['contacts'] . '%'];
        }
        if (!empty($this->parm['contacts_tel'] ?? '')) {
            $where[] = ['contacts_tel', 'LIKE', '%' . $this->parm['contacts_tel'] . '%'];
        }
        if (!empty($this->parm['business_license_pic'] ?? '')) {
            $where[] = ['business_license_pic', 'LIKE', '%' . $this->parm['business_license_pic'] . '%'];
        }
        if (!empty($this->parm['app_sn'] ?? '')) {
            $where[] = ['app_sn', '=', $this->parm['app_sn']];
        }
        $field = 'company_seal,company_id,company_no,company_name,company_addr,status,create_time,current_money,cumulative_money';
        $order = 'company_id DESC';
        // 列表查询
        $data = $this->companyModel->getAll($where, $field, $page, $pageSize, [], $order);
        if (empty($data)) {
            returnJson(1, '暂无相关数据');
        }
        foreach ($data as $k => &$v) {
            $v['status_name'] = $v['status'] == 2 ? '冻结' : '正常';
            $v['create_time'] = empty($v['create_time']) ? '' : date('Y年m月d日 H:i:s', $v['create_time']);
            $v['current_money'] = empty($v['current_money']) ? 0 : formatMoney($v['current_money'], 2);
            $v['cumulative_money'] = empty($v['cumulative_money']) ? 0 : formatMoney($v['cumulative_money'], 2);
            $v['company_seal'] = UploadImgPath($v['company_seal']);
        }
        // 数量查询
        $count = $this->companyModel->getCount($where);
        $info = ['limit' => $pageSize, 'page_current' => $page, 'page_sum' => ceil($count / $pageSize)];
        returnJson(0, '获取成功', $data, $count, $info);
    }

    // 状态操作
    public function changeStatus()
    {
        // 接收参数
        if (empty($this->parm['company_id'] ?? '')) {
            returnJson(-1001, '缺少参数ID');
        }
        $info = $this->companyModel->getOne(['company_id' => $this->parm['company_id']], 'status');
        if (empty($info)) {
            returnJson(-1001, '企业不存在');
        }
        $status = 2;
        $msg = '冻结';
        if ($info['status'] == 2) {
            $status = 1;
            $msg = '启用';
        }
        $res = $this->companyModel->edit(['company_id' => $this->parm['company_id']], ['status' => $status]);
        if ($res) {
            returnJson(0, $msg . '成功');
        }
        returnJson(1, $msg . '失败');
    }

    // 处理新增企业
    public function add()
    {
        // 接收参数
        if (empty($this->parm['app_sn'] ?? '')) {
            returnJson(-1001, "请选择应用");
        }
        if (empty($this->parm['company_no'] ?? '')) {
            returnJson(-1001, "请设置企业编号");
        }
        if ($this->parm['admin_password'] != $this->parm['admin_password1']) {
            returnJson(-1001, '密码不一致，请重新输入');
        }
        if (!empty($this->parm['telphone']) && !isPhone($this->parm['telphone'])) {
            returnJson(-1001, "请填写正确的企业电话");
        }
        if (!empty($this->parm['contacts_tel']) && !isMobile($this->parm['contacts_tel'])) {
            returnJson(-1001, "请填写正确的联系人电话");
        }
        //新增------滳滳打水处理页面
        if($this->parm['app_sn'] !='water2018'){
            if (empty($this->parm['company_name'] ?? '')) {
                returnJson(-1001, "请填写企业名称");
            }
            if (empty($this->parm['business_license_pic'] ?? '')) {
                returnJson(-1001, "请填写企业营业执照编号");
            }
            if (empty($this->parm['company_addr'] ?? '')) {
                returnJson(-1001, "请填写企业地址");
            }

            if (empty($this->parm['esign_config']['name'])) {
                returnJson(-1001, "企业名称不能为空");
            }
            if (empty($this->parm['esign_config']['organCode'])) {
                returnJson(-1001, "组织机构代码号或社会信用代码号或工商注册号不能为空");
            }
            if (!empty($this->parm['esign_config']['mobile']) && !isMobile($this->parm['esign_config']['mobile'])) {
                returnJson(-1001, "请输入正确的手机号码格式");
            }
            if (!empty($this->parm['esign_config']['email']) && !inge_isemail($this->parm['esign_config']['email'])) {
                returnJson(-1001, "请输入正确的邮箱格式");
            }

            if ($this->parm['esign_config']['userType'] == 1) {
                if (empty($this->parm['esign_config']['agentName'])) {
                    returnJson(-1001, "代理人姓名不能为空");
                }
                if (empty($this->parm['esign_config']['agentIdNo'])) {
                    returnJson(-1001, "代理人证件号不能为空");
                }
                if (!checkIdCard($this->parm['esign_config']['agentIdNo'])) {
                    returnJson(-1001, "请输入正确的代理人证件号");
                }
            } else if ($this->parm['esign_config']['userType'] == 2) {
                if (empty($this->parm['esign_config']['legalName'])) {
                    returnJson(-1001, "法人姓名不能为空");
                }
                if (empty($this->parm['esign_config']['legalIdNo'])) {
                    returnJson(-1001, "法人证件号不能为空");
                }
                if (!checkIdCard($this->parm['esign_config']['legalIdNo'])) {
                    returnJson(-1001, "请输入正确的法人证件号");
                }
            }

        }
        if (empty($this->parm['sms_config'])) {
            returnJson(-1001, "请填写短信配置内容");
        }
        if (empty($this->parm['sms_config']['uid'])) {
            returnJson(-1001, "请填写短信账号");
        }
        if (empty($this->parm['sms_config']['passwd'])) {
            returnJson(-1001, "请填写短信密码");
        }
        if (empty($this->parm['sms_config']['content'])) {
            returnJson(-1001, "请填写短信内容");
        }
        $cloud_company_no = $this->createSn($this->parm['company_no']);
        $data['company_no'] = $cloud_company_no;
        $data['company_name'] = $this->parm['company_name']??'';
        $data['short_name_en'] = $this->parm['short_name_en']??'';
        $data['business_license_pic'] = $this->parm['business_license_pic']??'';
        $data['company_addr'] = $this->parm['company_addr'];
        $data['telphone'] = $this->parm['telphone']??'';
        $data['contacts'] = $this->parm['contacts']??'';
        $data['contacts_tel'] = $this->parm['contacts_tel']??'';
        $data['seal_code'] = $this->parm['seal_code']??'';
        $data['remarks'] = $this->parm['remarks']??'';
        $data['create_time'] = time();
        $data['app_sn'] = $this->parm['app_sn']??'';
        // CRM账户
        $admin['account'] = !empty($this->parm['admin_account'] ?? '') ? $this->parm['admin_account'] : $cloud_company_no;
        $data['account'] = $admin['account'];
        // 判断唯一性
        $only = $this->onlyCompany($data['company_name'], $data['business_license_pic'], $admin['account']);
        if (!$only) {
            return $only;
        }

        //  开启事务
        Db::startTrans();
        try {
            // 1-- 添加企业
            $company_id = $this->companyModel->add($data);

            // 2-- 新增管理员信息 //修改密码在各自的端进行处理
            $admin['password'] = !empty($this->parm['admin_password'] ?? '') ? $this->parm['admin_password'] : 123456;
            $admin['company_id'] = $company_id;
            $admin['phone'] = $this->parm['contacts_tel']??'';
            $admin['name'] = $this->parm['contacts']??'';
            $admin['status'] = 1;
            $admin['add_time'] = time();
            $admin['is_admin'] = 1;
            $admin['address'] = $this->parm['company_addr']??'';
            if (!empty($this->parm['img_config'] ?? '')) {
                $admin['img_config'] = $this->parm['img_config'];
            }
            $admin['company_name'] = $data['company_name'];

            $api_host = $this->applicationsModel->getApiHost($this->parm['app_sn']);

            //新增----请求滳滳打水公司接口
            if($this->parm['app_sn'] == 'water2018'){
                // 2.1-- 请求滳滳打水接口添加
                $shang_data=[
                    'company_no'=>$data['company_no'],
                    'account'=>$data['account'],
                    'password'=>$admin['password'],
                    'phone'=>$admin['phone'],
                    'name'=>$admin['name'],
                ];
                $url = $api_host . 'Boss/Company/addAccount';
                $res = http_post($url, json_encode($shang_data));
                /*if ($res['code'] != 1000) {
                    returnJson(1, $res['message']);
                }*/
            }else{
                // 2.1-- 请求crm接口添加
                $url = $api_host . $this->api_url['addAccount'];
                $res = http_post($url, json_encode($admin));
                /*if ($res['code'] != 1000) {
                    returnJson(1, $res['message']);
                }*/
            }

            // 3-- 添加企业配置
            $config['company_id'] = $company_id;
            $config['create_time'] = time();
            if (!empty($this->parm['wx_config'] ?? '')) {
                $config['wx_config'] = json_encode($this->parm['wx_config']);
            }
            if (!empty($this->parm['spread_wx_config'] ?? '')) {
                $config['spread_wx_config'] = json_encode($this->parm['spread_wx_config']);
            }
            if (!empty($this->parm['engineer_wx_config'] ?? '')) {
                $config['engineer_wx_config'] = json_encode($this->parm['engineer_wx_config']);
            }
            if (!empty($this->parm['mp_config'] ?? '')) {
                $config['mp_config'] = json_encode($this->parm['mp_config']);
            }
            if (!empty($this->parm['img_config'] ?? '')) {
                $config['img_config'] = json_encode($this->parm['img_config']);
            }
            if (!empty($this->parm['esign_config'] ?? '')) {
                $config['esign_config'] = json_encode($this->parm['esign_config']);
            }
            if (!empty($this->parm['pay_config'] ?? '')) {
                $config['pay_config'] = json_encode($this->parm['pay_config']);
            }
            if(!empty($this->parm['sms_config'])){
                $config['sms_config'] = json_encode($this->parm['sms_config']);
            }
            $this->companyConfigModel->add($config);

            // 事务提交
            Db::commit();
            //生成企业印章
            $seal_api_url = $api_host . $this->api_url['createSeal'];
            if(!empty($this->parm['seal_code'])){
                $seal_result = http_post($seal_api_url, json_encode(['seal_code' => $this->parm['seal_code']]));
                if ($seal_result['code'] != 1000) {
                    returnJson(1, $seal_result['message']);
                }
                $edit_data['company_seal'] = $seal_result['data']['company_seal'] ?? '';
                unset($where);
                $where['company_id'] = $company_id;
                $this->companyModel->edit($where, $edit_data);
            }

            returnJson(0, "添加成功");
        } catch (\Exception $e) {
            // 事务回滚
            Db::rollback();
            returnJson(1, "添加失败" . $e->getMessage());
        }

    }

    // 处理编辑企业
    public function edit()
    {
        // 接收参数
        if (empty($this->parm['app_sn'] ?? '')) {
            returnJson(-1001, "请选择应用");
        }
        if (empty($this->parm['company_no'] ?? '')) {
            returnJson(-1001, "请设置企业编号");
        }
        if ($this->parm['admin_password'] != $this->parm['admin_password1']) {
            returnJson(-1001, '密码不一致，请重新输入');
        }
        if (!empty($this->parm['telphone']) && !isPhone($this->parm['telphone'])) {
            returnJson(-1001, "请填写正确的企业电话");
        }
        if (!empty($this->parm['contacts_tel']) && !isMobile($this->parm['contacts_tel'])) {
            returnJson(-1001, "请填写正确的联系人电话");
        }
        //新增------滳滳打水处理页面
        if($this->parm['app_sn'] !='water2018'){
            if (empty($this->parm['company_name'] ?? '')) {
                returnJson(-1001, "请填写企业名称");
            }
            if (empty($this->parm['business_license_pic'] ?? '')) {
                returnJson(-1001, "请填写企业营业执照编号");
            }
            if (empty($this->parm['company_addr'] ?? '')) {
                returnJson(-1001, "请填写企业地址");
            }

            if (empty($this->parm['esign_config']['name'])) {
                returnJson(-1001, "企业名称不能为空");
            }
            if (empty($this->parm['esign_config']['organCode'])) {
                returnJson(-1001, "组织机构代码号或社会信用代码号或工商注册号不能为空");
            }
            if (!empty($this->parm['esign_config']['mobile']) && !isMobile($this->parm['esign_config']['mobile'])) {
                returnJson(-1001, "请输入正确的手机号码格式");
            }
            if (!empty($this->parm['esign_config']['email']) && !inge_isemail($this->parm['esign_config']['email'])) {
                returnJson(-1001, "请输入正确的邮箱格式");
            }

            if ($this->parm['esign_config']['userType'] == 1) {
                if (empty($this->parm['esign_config']['agentName'])) {
                    returnJson(-1001, "代理人姓名不能为空");
                }
                if (empty($this->parm['esign_config']['agentIdNo'])) {
                    returnJson(-1001, "代理人证件号不能为空");
                }
                if (!checkIdCard($this->parm['esign_config']['agentIdNo'])) {
                    returnJson(-1001, "请输入正确的代理人证件号");
                }
            } else if ($this->parm['esign_config']['userType'] == 2) {
                if (empty($this->parm['esign_config']['legalName'])) {
                    returnJson(-1001, "法人姓名不能为空");
                }
                if (empty($this->parm['esign_config']['legalIdNo'])) {
                    returnJson(-1001, "法人证件号不能为空");
                }
                if (!checkIdCard($this->parm['esign_config']['legalIdNo'])) {
                    returnJson(-1001, "请输入正确的法人证件号");
                }
            }

        }
        if (empty($this->parm['sms_config'])) {
            returnJson(-1001, "请填写短信配置内容");
        }
        if (empty($this->parm['sms_config']['uid'])) {
            returnJson(-1001, "请填写短信账号");
        }
        if (empty($this->parm['sms_config']['passwd'])) {
            returnJson(-1001, "请填写短信密码");
        }
        if (empty($this->parm['sms_config']['content'])) {
            returnJson(-1001, "请填写短信内容");
        }

        $api_host = $this->applicationsModel->getApiHost($this->parm['app_sn']);//接口地址
        // 企业数据
        $data['company_name'] = $this->parm['company_name']??'';
        $data['short_name_en'] = $this->parm['short_name_en']??'';
        $data['business_license_pic'] = $this->parm['business_license_pic']??'';
        $data['company_addr'] = $this->parm['company_addr']??'';
        $data['telphone'] = $this->parm['telphone']??'';
        $data['contacts'] = $this->parm['contacts']??'';
        $data['contacts_tel'] = $this->parm['contacts_tel']??'';
        $data['seal_code'] = $this->parm['seal_code']??'';
        $data['remarks'] = $this->parm['remarks']??'';

        // 获取编辑之前的数据
        $where['company_id'] = $this->parm['id'];
        $company_data = $this->companyModel->getOne($where);
        // 判断企业名称一样不
        if ($company_data['company_name'] != $this->parm['company_name']??'') {
            // 判断唯一性
            $only = $this->onlyCompany($data['company_name'], $data['business_license_pic'], 0, 2);
            if (!$only) {
                return $only;
            }
        }

        // 开启事务
        Db::startTrans();
        try {
            // 1-- 编辑企业
            $where['company_id'] = $this->parm['id'];
            $this->companyModel->edit($where, $data);

            // 2-- 编辑管理员信息
            $admin['password'] = $this->parm['admin_password']??'';
            $admin['account'] = $this->parm['admin_account']??'';
            $admin['company_id'] = $this->parm['id']??'';
            $admin['phone'] = $this->parm['contacts_tel']??'';
            $admin['name'] = $this->parm['contacts']??'';
            $admin['address'] = $this->parm['company_addr']??'';
            if (!empty($this->parm['img_config'] ?? '')) {
                $admin['img_config'] = $this->parm['img_config'];
            }
            if($this->parm['app_sn'] == 'water2018'){
                // 2.1-- 请求滳滳打水接口添加
                $shang_data=[
                    'company_no'=>$this->parm['company_no'],
                    'account'=>$this->parm['admin_account'],
                    'password'=>$admin['password'],
                    'phone'=>$admin['phone'],
                    'name'=>$admin['name'],
                ];
                $url = $api_host . 'boss/Company/addAccount';
                $res = http_post($url, json_encode($shang_data));
                /* if ($res['code'] != 1000) {
                     returnJson(1, $res['message']);
                 }*/
            }else{
                // 2.1-- 请求crm接口添加
                $url = $api_host . $this->api_url['editAccount'];
                $res = http_post($url, json_encode($admin));
                /*if ($res['code'] != 1000) {
                    returnJson(0, $res['message']);
                }*/
            }
            // 编辑企业配置--由于生成印章时需要该部分配置，所以此部分不能放在事务中
            $config['update_time'] = time();
            if (!empty($this->parm['wx_config'] ?? '')) {
                $config['wx_config'] = json_encode($this->parm['wx_config']);
            }
            if (!empty($this->parm['spread_wx_config'] ?? '')) {
                $config['spread_wx_config'] = json_encode($this->parm['spread_wx_config']);
            }
            if (!empty($this->parm['engineer_wx_config'] ?? '')) {
                $config['engineer_wx_config'] = json_encode($this->parm['engineer_wx_config']);
            }
            if (!empty($this->parm['mp_config'] ?? '')) {
                $config['mp_config'] = json_encode($this->parm['mp_config']);
            }
            if (!empty($this->parm['img_config'] ?? '')) {
                $config['img_config'] = json_encode($this->parm['img_config']);
            }
            if (!empty($this->parm['esign_config'] ?? '')) {
                $config['esign_config'] = json_encode($this->parm['esign_config']);
            }
            if (!empty($this->parm['pay_config'] ?? '')) {
                $config['pay_config'] = json_encode($this->parm['pay_config']);
            }
            if(!empty($this->parm['sms_config'])){
                $config['sms_config'] = json_encode($this->parm['sms_config']);
            }

            $this->companyConfigModel->edit($where, $config);
            $this->redis->hdel('cloud_company_config_data', $this->parm['id']);//删除redis缓存数据
            $this->redis->hdel('cloud_company_info_data', $this->parm['id']);//删除redis缓存数据
            // 事务提交
            Db::commit();
            //生成企业印章--由于该部分需要企业配置信息，放在同一事务中将无法生成
            if (empty($company_data['company_seal'])) {
                $seal_api_url = $api_host . $this->api_url['createSeal'];
                $headers[] = "company:" . $this->parm['id'];
//                if(!empty($this->parm['seal_code'])){
                    $seal_result = http_post($seal_api_url, json_encode(['seal_code' => $this->parm['seal_code']??'']),false, $headers);
                    if ($seal_result['code'] != 1000) {
                        returnJson(1, $seal_result['message']);
                    }
                    $edit_data['company_seal'] = $seal_result['data']['url'] ?? '';
                    unset($where);
                    $where['company_id'] = $this->parm['id'];
                    $this->companyModel->edit($where, $edit_data);
               // }
            }

            returnJson(0, "编辑成功");
        } catch (\Exception $e) {
            // 事务回滚
            Db::rollback();
            returnJson(1, "编辑失败" . $e->getMessage());
        }


    }

    // 企业详情
    public function getDetail()
    {
        // 接收参数
        $company_id = $this->parm['company_id'] ?? '';
        $o_sn = $this->parm['o_sn'] ?? '';
        $a_sn = $this->parm['a_sn'] ?? '';

        if (empty($company_id)) {
            returnJson(0, '缺少参数');
        }
        $company_info = $this->accountModel->getCompanyInfo($company_id, $o_sn, $a_sn);
        if (empty($company_info)) {
            returnJson(0, '企业信息错误');
        }
        $data = $company_info;
        $data['money_sum'] = 0;
        if (!empty($company_info['account_id'])) {
            $wheres[] = ['account_id', '=', $company_info['account_id']];
            $wheres[] = ['source', 'IN', [3, 4]];
            $wheres[] = ['type', '=', 2];
            $firstday = date('Y-m-01 00:00:00', strtotime(date("Y-m-d")));  // 本月开始时间
            $lastday = date('Y-m-d 23:59:59', strtotime("$firstday +1 month -1 day")); // 本月结束时间
            $wheres[] = ['create_time', 'BETWEEN', [strtotime($firstday), strtotime($lastday)]];
            // 本月消费金额总和
            $money_sum = $this->accountRecordModel->getSum($wheres, [], 'money');
            $data['money_sum'] = formatMoney($money_sum, 2);
        }
        // 数据转换
        $data['current_money'] = $data['current_money'] ? formatMoney($data['current_money']) : 0;
        $data['total_money'] = $data['total_money'] ? formatMoney($data['total_money']) : 0;
        $data['threshold_money'] = $data['threshold_money'] ? formatMoney($data['threshold_money']) : 0;
        $data['tel'] = $company_info['contacts_tel'];
        $data['contacts_tel'] = yc_phone($company_info['contacts_tel']);

        //获取运营中心的信息
        if (!empty($o_sn) || !empty($a_sn)) {
            $send_post['o_sn'] = $o_sn;
            $send_post['a_sn'] = $a_sn;
            $send_post['company_id'] = $company_id;
            $api_host = $this->applicationsModel->getApiHost($company_info['app_sn']);//接口地址
            $url = $api_host . 'Boss/Company/getOperationAdministrativeInfo';
            $result = http_post($url, json_encode($send_post));

            $data['tel'] = $result['data']['phone'];
            $data['contacts_tel'] = yc_phone($result['data']['phone']);
            $data['contacts'] = $result['data']['name'];
        }


        returnJson(1, '获取成功', $data);
    }


    // 预警阈值开关
    public function operationSwitch()
    {
        // 接收参数
        $company_id = $this->parm['company_id'] ?? '';
        $o_sn = $this->parm['o_sn'] ?? '';
        $a_sn = $this->parm['a_sn'] ?? '';

        if (empty($company_id)) {
            returnJson(0, '缺少参数');
        }
        // 查询当前开关值
        $where[] = ['company_id', '=', $company_id];
        //$info = $this->companyModel->getOne($where, 'threshold_switch');
        $info = $this->accountModel->getCompanyInfo($company_id, $o_sn, $a_sn);
        if (empty($info)) {
            returnJson(0, '企业账户不存在');
        }
        $data['threshold_switch'] = 1;
        $msg = '启用';
        if ($info['threshold_switch'] == 1) {
            $data['threshold_switch'] = 2;
            $msg = '关闭';
        }
        // 编辑开关
        $res = $this->accountModel->edit(['id' => $info['account_id']], $data);
        if ($res) {
            returnJson(1, $msg . '成功');
        }
        returnJson(0, $msg . '失败');
    }

    // 修改预警阀值
    public function thresholdMoney()
    {
        // 接收参数
        $company_id = $this->parm['company_id'] ?? '';
        $o_sn = $this->parm['o_sn'] ?? '';
        $a_sn = $this->parm['a_sn'] ?? '';

        $threshold_money = $this->parm['threshold_money'] ?? '';
        if (empty($company_id) || empty($threshold_money)) {
            returnJson(0, '缺少参数');
        }
        $where[] = ['company_id', '=', $company_id];
        $info = $this->accountModel->getCompanyInfo($company_id, $o_sn, $a_sn);
        if (empty($info)) {
            returnJson(0, '企业账户信息错误');
        }

        if ($info['threshold_money'] == formatMoney($threshold_money, 1)) {
            returnJson(1, '无修改');
        }
        $data['threshold_money'] = formatMoney($threshold_money, 1);
        $data['threshold_switch'] = 1;
        $res = $this->accountModel->edit(['id' => $info['account_id']], $data);
        if ($res) {
            returnJson(1, '修改成功');
        }
        returnJson(0, '修改失败');
    }

    // 修改手机号码
    public function editPhone()
    {
        // 接收参数
        $tel = $this->parm['tel'] ?? '';
        $company_id = $this->parm['company_id'] ?? '';
        if (empty($tel) || empty($company_id)) {
            returnJson(0, '缺少参数');
        }
        $where[] = ['company_id', '=', $company_id];
        $data['contacts_tel'] = $tel;
        // 修改
        $res = $this->companyModel->edit($where, $data);
        if ($res) {
            returnJson(1, '修改成功');
        }
        returnJson(0, '修改失败');
    }

    // 小程序端获取企业详情
    public function getCompany()
    {
        // 接收参数
        $company_id = $this->parm['company_id'] ?? '';
        $company_no = $this->parm['company_no'] ?? '';
        if (empty($company_id) && empty($company_no)) {
            returnJson(0, '缺少参数');
        }
        $where = [];
        if (!empty($company_id)) {
            $where[] = ['company_id', '=', $company_id];
        }
        if (!empty($company_no)) {
            $where[] = ['company_no', '=', $company_no];
        }
        $field = '*';
        $data = $this->companyModel->getOne($where, $field);
        if ($data) {
            $data['company_seal'] = config('api.qi_niu_url') . $data['company_seal'];
            returnJson(1000, '获取企业信息成功', $data);
        }
        returnJson(-1000, '暂无数据');
    }

    // 获取企业配置信息
    public function getCompayConfig()
    {
        // 接收参数
        $company_id = $this->parm['company_id'] ?? '';
        $company_no = $this->parm['company_no'] ?? '';

        if (empty($company_id) && empty($company_no)) {
            returnJson(0, '缺少参数');
        }
        if(!empty($company_id)){
            $where[] = ['a.company_id', '=', $company_id]; // 企业ID
        }
        if(!empty($company_no)){
            $where[] = ['c.company_no', '=', $company_no]; // 企业编号
        }
        $field = 'a.*';
        $join=[
            ['company c','c.company_id=a.company_id','left']
        ];
        $data = $this->companyConfigModel->getOne($where, $field,$join);
        if ($data) {
            $data['link_config'] = empty($data['link_config']) ? '' : json_decode($data['link_config'], true);
            $img_config = empty($data['img_config']) ? '' : json_decode($data['img_config'], true);
            $data['mp_config'] = empty($data['mp_config']) ? '' : json_decode($data['mp_config'], true);
            $data['wx_config'] = empty($data['wx_config']) ? '' : json_decode($data['wx_config'], true);
            $data['spread_wx_config'] = empty($data['spread_wx_config']) ? '' : json_decode($data['spread_wx_config'], true);
            $data['esign_config'] = empty($data['esign_config']) ? '' : json_decode($data['esign_config'], true);
            $data['sms_config'] = empty($data['sms_config']) ? '' : json_decode($data['sms_config'], true);
            $data['engineer_wx_config'] = empty($data['engineer_wx_config']) ? '' : json_decode($data['engineer_wx_config'], true);
            $data['pay_config'] = empty($data['pay_config']) ? '' : json_decode($data['pay_config'], true);
            $img_config['admin_image'] = empty($img_config['admin_image']) ? '' : uploadImgPath($img_config['admin_image']);
            $img_config['image'] = empty($img_config['image']) ? '' : uploadImgPath($img_config['image']);
            $data['img_config'] = $img_config;

            returnJson(1, '获取成功', $data);
        }
        returnJson(0, '未查询到');
    }

    /**
     *   企业唯一性
     * @param $company_name  企业名称
     * @param $business_license_pic 营业执照编号
     * @param $admin_account  登录账号
     * @param int $type 1新增 2编辑
     * @return bool
     */
    public function onlyCompany($company_name, $business_license_pic, $admin_account, $type = 1)
    {
        $count = $this->companyModel->getCount(['company_name' => $company_name]);
        $limit = 0;
        if ($type == 2) {
            $limit = 1;
        }
        if ($count > $limit) {
            returnJson(-1002, "该企业名称已经存在");
        }
        $business_license_pic_count = $this->companyModel->getCount(['business_license_pic' => $business_license_pic]);
        if ($business_license_pic_count > $limit) {
            returnJson(-1002, "该营业执照编号已经存在");
        }
        return true;
    }

    /**
     *   生成唯一编号
     * @param string $key
     * @param string $prefix
     * @param int $type
     * @return int
     */
    public function createSn($sn = '')
    {
        if (!empty($sn)) {
            $vo = $this->companyModel->getOne(['company_no' => $sn], 'company_id');
            if (!empty($vo)) {
                return $vo;
            }
        }
        do {
            $str = mt_rand(10000000, 19999999);//企业编号1开头
            $vo = $this->companyModel->getOne(['company_no' => $str], 'company_id');
            if (empty($vo)) {
                break;
            }
        } while (true);
        return $str;
    }

}